package com.tongqu.protocol;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.tongqu.message.LoginMessage;
import com.tongqu.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
//@ChannelHandler.Sharable   is not allowed to be shared
public class MessageCodec extends MessageToMessageCodec<ByteBuf, Message> {
    public void channelActive(ChannelHandlerContext ctx)  {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("连接建立....");
        System.out.println("客户端IP: " + sc.localAddress().getHostString());
        System.out.println("客户端端口: " + sc.localAddress().getPort());
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> outList)  {
        ByteBuf out = ctx.alloc().buffer();
        String json= JSON.toJSONString(msg);
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        out.writeBytes(bytes);
        log.info("编码结束----------------------------------出站");
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("开始解码********************************接收信息");
        int length = in.readableBytes();
        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length);
        String json = new String(bytes,StandardCharsets.UTF_8);
        log.info(json);
        Message message=JSON.parseObject(json,Message.class);
        System.out.println(message);
        System.out.println(message);
        System.out.println(message);
        System.out.println(message);
        System.out.println(message);
        System.out.println(message);
        System.out.println(message);
        log.debug("{}", message);
        out.add(message);
        log.info("解码完成********************************接收信息");

    }


    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("连接断开....");
        System.out.println("客户端IP: " + sc.localAddress().getHostString());
        System.out.println("客户端端口: " + sc.localAddress().getPort());
        ctx.writeAndFlush("asd".getBytes());
    }


}